package com.cloud.wms.http.observer;

import android.content.Context;
import android.content.Intent;

import com.cloud.core.http.BaseObserver;
import com.cloud.core.http.error.ApiException;
import com.cloud.core.http.error.ERROR;
import com.cloud.core.http.error.ExceptionEngine;
import com.cloud.wms.ui.main.activity.LoginActivity;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public abstract class LoadingObserver<T> extends BaseObserver<T> implements ProgressCancelListener {
    private Context mContext;

    private ProgressDialogHandler mHandler;
    private Disposable disposable;

    public LoadingObserver(Context context) {
        this(context, false);
    }

    public LoadingObserver(Context context, boolean forceCanceled) {
        this.mContext = context;
        mHandler = new ProgressDialogHandler(mContext, forceCanceled, this);
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        disposable = d;
        showProgressDialog();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        ApiException apiException = ExceptionEngine.handleException(e);
        if (apiException.code == ERROR.TOKEN_INVALID) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }
    }

    @Override
    public void onError(String msg) {
        dismissProgressDialog();
    }

    @Override
    public void dialogCanceled() {
        if (disposable != null) {
            disposable.dispose();
        }
        if (mContext != null) {
            mContext = null;
        }
    }

    private void showProgressDialog() {
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.SHOW_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.DISMISS_DIALOG).sendToTarget();
            mHandler = null;
        }
    }
}
